﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Skymate.Lyit.RabbitMq
{
    using System.Reflection;

    using Abp;
    using Abp.Dependency;
    using Abp.Events.Bus;
    using Abp.Modules;

    using EasyNetQ;

    [DependsOn(typeof(AbpKernelModule))]
    public class RabbitMqModule:AbpModule
    {

        public override void Initialize()
        {
            this.IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

        }

    }
    
    public interface IBusProvider : ITransientDependency
    {
        IBus MessageBus();
    }

    public interface IEventMq : ITransientDependency
    {
        void Pulish(EventData data);
    }

    public class EventMq : IEventMq
    {
        private readonly IBusProvider _busProvider;

        public EventMq(IBusProvider busProvider)
        {
            this._busProvider = busProvider;
        }

        public void Pulish(EventData data)
        {
            using (var bus = this._busProvider.MessageBus())
            {
                try
                {
                    bus.Publish(data);
                }
                catch (EasyNetQException ex)
                {
                    //处理连接消息服务器异常 
                }
            }
            //throw new NotImplementedException();
        }
    }

    public class BusProvider : IBusProvider
    {
        public IBus MessageBus()
        {
            string connString = "host=127.0.0.1:5672;virtualHost=/;username=admin;password=123qwe";
            if (string.IsNullOrEmpty(connString))
            {
                throw new Exception("messageserver connection string is missing or empty");
            }
            return RabbitHutch.CreateBus(connString);
        }
    }
    

}
